package com.autumn.algorithm;

/**
 * 环形链表II
 * 给定一个链表，返回链表开始入环的第一个节点，若无环则返回null
 * 不允许修改给定的链表
 */
public class Algorithm10DetectCycle {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slowPtr = head, fastPtr = head;
        boolean loopExists = false;
        while (fastPtr.next != null && fastPtr.next.next != null) {
            slowPtr = slowPtr.next;
            fastPtr = fastPtr.next.next;
            if (slowPtr == fastPtr) {
                loopExists = true;
                break;
            }
        }
        //环存在
        if (loopExists) {
            slowPtr = head;
            if (slowPtr != fastPtr) {
                slowPtr = slowPtr.next;
                fastPtr = slowPtr.next;
            }
            //返回环的开始节点
            return slowPtr;
        }
        return null;
    }
}
